/**
 * 
 */
package com.gson.db;

import java.sql.*;

/**
 * @作者 Stone
 * @创建日期 2013-10-14 上午2:07:01
 * @版本 V1.0
 * @类说明
 */
public class MysqlDb {

	public static void DB(String sql) {
		// 驱动程序名
		String driver = "com.mysql.jdbc.Driver";
		// url指向的数据库
		String url = "jdbc:mysql://localhost:3306/test";
		// MYSQL用户名
		String user = "root";
		// MYSQL密码
		String password = "root";
		try {
			// 加载驱动程序
			Class.forName(driver);
			// 连接数据库
			Connection conn = DriverManager.getConnection(url, user, password);
			// statement用来执行SQL语句
			Statement statement = conn.createStatement();

			int rs = statement.executeUpdate(sql); // 执行UPDATE INSERT DELETE用
													// executeUpdate 返回INT类型
			// ResultSet rs = statement.executeQuery(sql); 执行select 用
			// executeQuery 返回ResultSet 类型

			/*
			 * String name = null; while(rs.next()){ name =
			 * rs.getString("name"); System.out.println(name); }
			 */

		} catch (ClassNotFoundException e) {
			System.out.println("Sorry,I can not find dirver");
			e.printStackTrace();

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();

		}

	}
	
	public ResultSet search(String sql) {
		ResultSet rs = null;
		try {
			// 连接数据库
			Connection conn = getConnection();
								
			// statement用来执行SQL语句
			Statement statement = conn.createStatement();
			
			rs = statement.executeQuery(sql); //执行select 用executeQuery 返回ResultSet 类型
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	public static synchronized Connection getConnection() {
		Connection conn = null;
		/*****1. 填写数据库相关信息(请查找数据库详情页)*****/
		String databaseName = " DXczKKxdSnjrcPUkEBRz"; 
		String host = "sqld.duapp.com";
		String port = "4050";
		String username = " pVn9o1CHtxN7S9D04hGuewD7";//用户名(api key);
		String password = "5W82qCr6THsnvPSvxYQ5Dzgl3qudNvLw";//密码(secret key)
		String driverName = "com.mysql.jdbc.Driver";
		String dbUrl = "jdbc:mysql://";
		String serverName = host + ":" + port + "/";
		String connName = dbUrl + serverName + databaseName;
		
		try {
			// 加载驱动程序
			Class.forName(driverName);
			// 连接数据库
			conn = DriverManager.getConnection(connName, username, password);
		} catch (ClassNotFoundException e) {
			System.out.println("Sorry,I can not find dirver");
			e.printStackTrace();

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();

		}
		return conn;
	}
}
